package other.her.paas.travel;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.ChucBaogMx__c;
import com.rkhd.platform.sdk.data.model.ChucBaog__c;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.her.paas.utils.HCXObjectService;
import other.her.paas.utils.ResultVo;

import java.util.*;

/**
 * @Description: 添加【出差总结报告】明细
 * @Author: 黎炎松
 * @Date: 2024/11/18 15:17
 */
public class AddTravelDetail implements Trigger  {

    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "添加【出差总结报告】明细 ==> ";

    private static Map<Long, Long> entityTypeMap = new HashMap<Long, Long>(){{
        put(3480956805782120L, 3499432082987628L);
        put(3480979428022850L, 3499476325702283L);
    }};

    // 互动方式转换
    private static Map<Long, Integer> hdfsChangeMap = new HashMap<Long, Integer>(){{
        put(11010011100001L, 1);
        put(11010011100002L, 2);
    }};

    /**
     * tregger 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        LOGGER.debug(LOGGER_MSG + "Trigger 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        for (XObject xObject : dataList) {
            dataResultList.add(new DataResult(true, "", xObject));
        }
        dealAddTravelDetail(dataList.get(0).getAttribute("id"));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        AddTravelDetail addTravelDetail = new AddTravelDetail();
        addTravelDetail.dealAddTravelDetail(3618364667976301L);
    }

    /**
     * 添加【出差总结报告】明细 （新增后如果明细为空则赋值）
     * @param travelId
     * @return
     */
    public ResultVo dealAddTravelDetail(Long travelId) {

        try {
            LOGGER.info(LOGGER_MSG + "开始处理: " + travelId);

            // 判断明细是否为空
            String sql = "select id from chucBaogMx__c where chucBaog__c = " + travelId;
            XObject xObject = HCXObjectService.queryOne(sql);
            LOGGER.info(LOGGER_MSG + "xObject:" + xObject);
            if (xObject != null) {
                LOGGER.info("当前【出差总结报告】有明细无需处理");
                return ResultVo.success(" 当前【出差总结报告】有明细无需处理");
            }

            // 查询【开始日期】~【结束日期】当前【所有人】的拜访记录 chucBaog__c
            ChucBaog__c chucBaog = new ChucBaog__c();
            chucBaog.setId(travelId);
            chucBaog = HCXObjectService.get(chucBaog);
            sql = String.format("select id,dbcRelation26,startTime,content,customItem131__c,contactName,contactPhone,post__c,entityType,ownerId,fangShi__c " +
                    " from activityrecord where startTime between %s and %s and  ownerId = %s", chucBaog.getCustomItem3__c(), setTimestampTo23Hours(chucBaog.getCustomItem4__c()), chucBaog.getOwnerId());
            List<JSONObject> recordList = XoqlService.instance().query(sql).getRecords();
            LOGGER.info(LOGGER_MSG + "recordList:" + recordList);
            if (recordList.size() <= 0) {
                LOGGER.info("当前日期范围内无跟进记录");
                return ResultVo.success("当前日期范围内无跟进记录");
            }

            // 明细的业务类型
            Long entityType = entityTypeMap.get(chucBaog.getEntityType());

            List<ChucBaogMx__c> addList =new ArrayList<>();
            for (JSONObject record : recordList) {
                ChucBaogMx__c chucBaogMx = new ChucBaogMx__c();
                chucBaogMx.setEntityType(entityType);
                chucBaogMx.setChucBaog__c(travelId);
                chucBaogMx.setAccountName__c(record.getLong("dbcRelation26"));
                chucBaogMx.setInteractionTime__c(record.getLong("startTime"));
                chucBaogMx.setBaifMud__c(record.getString("content"));
                chucBaogMx.setResult__c(record.getString("customItem131__c"));
                chucBaogMx.setContacts__c(record.getString("contactName"));
                chucBaogMx.setPhone__c(record.getString("contactPhone"));
                chucBaogMx.setPost__c(record.getString("post__c"));
                chucBaogMx.setInteractiveMode__c(hdfsChangeMap.get(record.getLong("entityType")));
                chucBaogMx.setCreatedBy(record.getLong("ownerId"));
                chucBaogMx.setFangShi__c(record.getString("fangShi__c"));
                addList.add(chucBaogMx);
            }

            // 保存
            HCXObjectService.insertBatch(addList);

            LOGGER.info(LOGGER_MSG + "处理成功");
            return ResultVo.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("处理异常: " + e.getMessage());
        }
    }

    public Long setTimestampTo23Hours(Long timestamp) {
        Date date = new Date(timestamp);

        // 获取Calendar实例
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 将时间调整为23点（11PM）
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);

        // 将Calendar对象转回Date对象
        long timeInMillis = calendar.getTimeInMillis();
        System.out.println("timeInMillis = " + timeInMillis);
        return timeInMillis;
    }
}
